/*
5. 最长回文子串 https://leetcode.cn/problems/longest-palindromic-substring/
中等 2024/11/18
*/
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
    string longestPalindrome(string s) {
        if (s.empty()) return "";
        
        int start = 0, end = 0;
        for (int i = 0; i < s.size(); ++i) {
            int len1 = expandAroundCenter(s, i, i); // 奇数长度的回文
            int len2 = expandAroundCenter(s, i, i + 1); // 偶数长度的回文
            int len = max(len1, len2);
            if (len > end - start) {
                start = i - (len - 1) / 2;
                end = i + len / 2;
            }
        }
        return s.substr(start, end - start + 1);
    }
    
private:
    int expandAroundCenter(const string& s, int left, int right) {
        while (left >= 0 && right < s.size() && s[left] == s[right]) {
            --left;
            ++right;
        }
        return right - left - 1; // 返回回文的长度
    }
};
int main()
{
    Solution solution;
    string s1 = "babad"; // 示例1中的输入
    string s2 = "cbbd";  // 示例2中的输入

    cout << "最长回文子串'" << s1 << "': '" << solution.longestPalindrome(s1) << "'" << endl; // 应该输出 "bab" 或 "aba"
    cout << "最长回文子串'" << s2 << "': '" << solution.longestPalindrome(s2) << "'" << endl; // 应该输出 "bb"
    return 0;
}